<template>
  <view class="userinfo-page">
    <!-- 头部背景 -->
    <view class="header-bg"></view>

    <!-- 用户信息卡片 -->
    <view class="user-card">
      <!-- 头像上传 -->
      <view class="avatar-section" @click="changeAvatar">
        <image class="avatar" :src="formData.avatar || '../../static/missing-face.png'" mode="aspectFill"></image>
        <text class="tip">点击修改头像</text>
      </view>

      <!-- 表单区域 -->
      <view class="form-section">
        <uni-forms ref="form" :model="formData" :rules="rules">
          <!-- 用户名 -->
          <uni-forms-item label="用户名" name="username">
            <uni-easyinput v-model="formData.username" placeholder="请输入用户名" type="nickname" />
          </uni-forms-item>

          <!-- 邮箱 -->
          <uni-forms-item label="邮箱" name="email">
            <uni-easyinput v-model="formData.email" placeholder="请输入邮箱" />
          </uni-forms-item>

          <!-- 密码修改 -->
          <view class="password-item">
            <text class="label">密码</text>
            <text class="change-pwd" @click="showPasswordField = true">修改密码</text>
          </view>
          <uni-forms-item v-if="showPasswordField" name="password">
            <uni-easyinput type="password" v-model="formData.old_password" placeholder="请输入旧密码" />
            <uni-easyinput type="password" v-model="formData.password" placeholder="请输入新密码" />
          </uni-forms-item>
        </uni-forms>

        <!-- 保存按钮 -->
        <button class="save-btn" @click="submitForm">保存修改</button>

        <!-- 注销登录 -->
        <button class="save-btn" @click="logoutUser">注销登录</button>
      </view>
    </view>

    <!-- 弹窗 -->
    <uni-popup ref="popup" border-radius="10px 10px 0 0">
      <view class="popup-wrapper">
        <button class="popup-item" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">点击更换头像</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import aesEncrypt from '../../utils/encrypt'
export default {
  data() {
    return {
      //   Id          int    `json:"id"`
      // Avatar      string `json:"avatar"`
      // Username    string `json:"username"`
      // PhoneNumber string `json:"phone_number"` // 未实现
      // Email       string `json:"email"`
      // Password    string `json:"password"`
      // OldPassword string `json:"old_password"`
      // AESId       string `json:"a_id"`
      formData: {
        id: '',
        avatar: '',
        username: '未设置',
        email: '',
        old_password: '',
        password: '',
        a_id: ''
      },
      showPasswordField: false,
      isUploadFile: false,
      rules: {
        username: {
          rules: [{ required: true, errorMessage: '用户名不能为空' }]
        },
        email: {
          rules: [{ format: 'email', errorMessage: '邮箱格式不正确' }]
        },
        old_password: {
          rules: [{ minLength: 8, errorMessage: '密码至少8位' }]
        },
        password: {
          rules: [{ minLength: 8, errorMessage: '密码至少8位' }]
        }
      },
      aa: null
    }
  },
  onLoad() {
    this.loadUserData()
  },
  methods: {
    // 加载用户数据
    loadUserData() {
      // 模拟从全局或接口获取数据
      const user = getApp().globalData.userInfo || {}
      this.formData = {
        id: user.id,
        avatar: user.avatar || '',
        username: user.username || '未设置',
        email: user.email || '',
        password: '',
        old_password: ''
      }
    },

    async logoutUser() {
      // 清空用户登录缓存,同时删除数据库token
      const { data: res } = await uni.request({
        url: this.$domain.data + '/logoutUser',
        method: 'POST',
        header: getApp().globalData.header,
        data: {
          user_id: getApp().globalData.userInfo.id,
          token: getApp().globalData.header.Authorization
        }
      })
      // console.log(res)
      if (res.status != 200) {
        this.$checkStatus(res.status, res.message)
        return
      }

      uni.showToast({
        icon: 'success',
        title: '注销成功'
      })

      // 删除缓存
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')

      setTimeout(() => {
        uni.reLaunch({ url: '/pages/mine/index' })
      }, 500)
    },

    // 修改头像
    changeAvatar() {
      this.$refs.popup.open('bottom')
    },
    onChooseAvatar(e) {
      this.isUploadFile = true
      const avatar = e.detail.avatarUrl
      // console.log(avatar)
      this.formData.avatar = avatar
      this.$refs.popup.close()
    },

    // 提交表单
    submitForm() {
      this.$refs.form
        .validate()
        .then(async () => {
          uni.showLoading({ title: '保存中...' })
          let formData = { ...this.formData }

          if (formData.password !== '' && formData.old_password !== '') {
            // 获取AES密钥
            // 获取密钥，过期后重新拿
            if (this.aa == null || this.aa.et < new Date().getTime()) {
              const a = await uni.request({
                method: 'GET',
                url: this.$domain.data + '/userRegLogin'
              })

              if (a.data.status != 200) {
                this.$checkStatus(a.data.status)
                this.aa = null
                return
              }
              console.log(a.data.data)
              this.aa = JSON.parse(a.data.data)

              this.aa.id = String(this.getExId(a.data.data))
            }
            formData.a_id = String(this.aa.id)
            // 数据加密
            const pwd = aesEncrypt(formData.password, this.aa.a.s, this.aa.a.iv)
            const opwd = aesEncrypt(formData.old_password, this.aa.a.s, this.aa.a.iv)
            formData.password = pwd
            formData.old_password = opwd
          }

          // console.log(this.formData)
          if (this.isUploadFile) {
            uni.uploadFile({
              url: this.$domain.data + '/updateUserByUser',
              filePath: this.formData.avatar,
              name: 'avatar',
              formData: {
                user: JSON.stringify(formData)
              },
              success: (uploadRes) => {
                const res = JSON.parse(uploadRes.data)
                if (res.status !== 200) {
                  this.$checkStatus(res.status, res.message)
                  return
                }

                // 更新缓存
                uni.setStorageSync('userInfo', JSON.stringify(res.data))
                // 更新全局数
                getApp().globalData.userInfo = { ...res.data }
              }
            })
          } else {
            const { data: res } = await uni.request({
              url: this.$domain.data + '/updateUserByUser',
              method: 'POST',
              header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                Authorization: getApp().globalData.header.Authorization
              },
              data: {
                user: JSON.stringify(formData)
              }
            })

            if (res.status !== 200) {
              this.$checkStatus(res.status, res.message)
              return
            }
            // console.log(res)
            // 更新缓存
            uni.setStorageSync('userInfo', JSON.stringify(res.data))
            // 更新全局数
            getApp().globalData.userInfo = { ...res.data }
          }
          uni.hideLoading()
          uni.showToast({ title: '保存成功', icon: 'success' })
          this.showPasswordField = false
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            })
          }, 500)
        })
        .catch((err) => {
          console.log('验证失败:', err)
        })
    },
    getExId(jsonStr) {
      const arr = jsonStr.split(',')
      const ids = arr[arr.length - 1]
      const id = ids.split('}')[0].split(':')[1] + ''

      return id
    }
  }
}
</script>

<style lang="scss">
.popup-wrapper {
  background-color: #fff;
  width: 100vw;
  // height: 230upx;
  padding: 20upx;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .popup-item:nth-child(odd) {
    border-bottom: 5upx solid #f5f5f5;
  }

  button {
    background-color: #ffffff; /* 白色背景 */
    border: none;
    outline: none;
  }

  button::after {
    border: none;
    outline: none;
  }

  .popup-item {
    width: 100%;
    cursor: pointer;
    height: 80upx;
    margin-bottom: 10upx;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    // background-color: #ff6b81;
    color: #fea3a4;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 20upx;
  }
}

.userinfo-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;

  /* 头部背景 */
  .header-bg {
    height: 300upx;
    background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  }

  /* 用户卡片 */
  .user-card {
    margin: -150upx 30upx 0;
    padding: 40upx;
    background: #fff;
    border-radius: 20upx;
    box-shadow: 0 10upx 30upx rgba(0, 0, 0, 0.1);
    position: relative;
    z-index: 2;

    /* 头像区域 */
    .avatar-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 50upx;

      .avatar {
        width: 200upx;
        height: 200upx;
        border-radius: 50%;
        border: 5upx solid #fff;
        box-shadow: 0 0 20upx rgba(0, 0, 0, 0.1);
      }

      .tip {
        margin-top: 20upx;
        color: #999;
        font-size: 26upx;
      }
    }

    /* 表单区域 */
    .form-section {
      .password-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20upx 0;
        font-size: 30upx;

        .label {
          color: #666;
        }

        .change-pwd {
          color: #ff6b81;
        }
      }

      /* 保存按钮 */
      .save-btn {
        margin-top: 60upx;
        background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
        color: #fff;
        border-radius: 50upx;
        height: 90upx;
        line-height: 90upx;
        font-size: 32upx;
      }
    }
  }
}
</style>
